<?php

namespace app\admin\model\shop\market\coupon;

use app\shop\enums\coupon\CouponExpiryType;
use app\shop\library\datetime\TimeHelper;
use ba\Exception;
use think\Model;
use think\model\relation\BelongsTo;

/**
 * Center
 */
class Center extends Model
{
    // 表名
    protected $name = 'shop_coupon_center';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 字段类型转换
    protected $type = [
        'start_time'        => 'timestamp:Y-m-d H:i:s',
        'end_time'          => 'timestamp:Y-m-d H:i:s',
        'active_start_time' => 'timestamp:Y-m-d H:i:s',
        'active_end_time'   => 'timestamp:Y-m-d H:i:s',
    ];

    public function coupon(): BelongsTo
    {
        return $this->belongsTo(Coupon::class, 'coupon_id', 'id');
    }

    /**
     * 添加后
     * @param $model
     * @return void
     */
    protected static function onAfterInsert($model): void
    {
        if ($model->weigh == 0) {
            $pk = $model->getPk();
            if (strlen($model[$pk]) >= 19) {
                $model->where($pk, $model[$pk])->update(['weigh' => $model->count()]);
            } else {
                $model->where($pk, $model[$pk])->update(['weigh' => $model[$pk]]);
            }
        }
    }

    /**
     * 添加前
     * @param Model $model
     * @return Model
     * @throws Exception
     */
    public static function onBeforeInsert(Model $model): Model
    {
        $expiryType = $model->getData('expiry_type');
        if (!in_array($expiryType, [CouponExpiryType::FIXED_TIME, CouponExpiryType::FIXED_DAYS])) {
            throw new Exception('优惠券有效期错误');
        }

        $startTime = $endTime = 0;

        if ($expiryType == CouponExpiryType::FIXED_TIME) {
            list($startTime, $endTime) = $model->getData('expiry_time');
            $startTime = strtotime($startTime);
            $endTime   = strtotime($endTime);

            if ($startTime > $endTime) {
                throw new Exception('优惠券开始时间不能小于结束时间');
            }
        }
        if ($expiryType == CouponExpiryType::FIXED_DAYS) {
            $startTime = time();
            $endTime   = TimeHelper::afterDay($model->getData('expiry_days'), null, true) - 1;
        }

        if ($startTime == 0 || $endTime == 0) {
            throw new Exception('优惠券时间有误');
        }

        list($activeStartTime, $activeEndTime) = $model->getData('active_time');

        $model->remain_num        = $model->getData('total_num');
        $model->discount_ratio    /= 10;
        $model->start_time        = $startTime;
        $model->end_time          = $endTime;
        $model->active_start_time = strtotime($activeStartTime);
        $model->active_end_time   = strtotime($activeEndTime);

        return $model;
    }
}